package com.audaque.springboot.foshanupload.web.openfeigndemo.controller;

import com.audaque.springboot.foshanupload.core.component.ApplicationContextProvider;
import com.audaque.springboot.foshanupload.web.openfeigndemo.feign.api.FeignFeign;
import com.audaque.springboot.foshanupload.web.openfeigndemo.model.dto.FeignDto;
import com.audaque.springboot.foshanupload.web.openfeigndemo.model.req.FeignReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/feignTest")
public class FeignTestController {
    @Autowired
    private FeignFeign feignFeign;
    @Autowired
    private ApplicationContextProvider applicationContextProvider;

    @Autowired
    private ApplicationContext applicationContext;

    @GetMapping("/get1")
    public String get1() {
        long threadId = Thread.currentThread().getId();
        log.debug("threadId："+threadId);
        return feignFeign.get1();

    }

    @GetMapping("/get2/{param}")
    public String get2(@PathVariable("param") String param) {
        return feignFeign.get2(param);
    }


       @GetMapping("/get3/{param}")
    public String get3(@PathVariable("param") String param) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

           String canonicalName = FeignFeign.class.getCanonicalName();
           String methodName = "get2";

           /*通过Class对象来获取对象中的方指定法
            *第一个参数是class对象，第二个参数是方法名
            *第三个参数是可变参数(根据需求可传可不传)，需要传入参数的类型class对象(eg:String.class)
            */
           Method method = Arrays.stream(applicationContext.getBean(canonicalName).getClass().getMethods()).filter(m->m.getName().equals(methodName)).collect(Collectors.toList()).get(0);
           /*
            *执行方法
            *第一个参数是Method 对象，第二个参数是对象
            *第三个参数是可变参数(根据需求可传可不传)，需要传入调用方法的参数值
            */
           Object resultObj = ReflectionUtils.invokeMethod(method,applicationContext.getBean(canonicalName),new Object[]{"3"});
           return (String) resultObj;


    }






    @PostMapping("/post1")
    public FeignDto post1(@RequestBody FeignReq req) {
        return feignFeign.post1(req);

    }
}




